""" -*- coding: utf-8 -*-"""
from flask import Blueprint, request, jsonify, g, current_app
from models import db, User, Department
from extends.auth import authenticate, require_role
from werkzeug.security import generate_password_hash

user_bp = Blueprint('user', __name__, url_prefix='/users')


@user_bp.before_request
def before_request():
    return authenticate()


@user_bp.route('/register', methods=['POST'])
def register():
    """用户注册"""
    data = request.get_json()
    required_fields = ['name', 'password', 'phone', 'email', 'department_id']
    for field in required_fields:
        if field not in data or not str(data[field]).strip():
            return jsonify({'error': f'Missing required field: {field}'}), 400

    # 检查邮箱是否已存在
    if User.query.filter_by(email=data['email']).first():
        return jsonify({'error': 'Email already exists'}), 409

    # 检查部门是否存在
    department = Department.query.get(data['department_id'])
    if not department:
        return jsonify({'error': 'Department not found'}), 404

    # 设置默认角色
    role = data.get('role', 'staff')

    new_user = User(
        name=data['name'],
        phone=data['phone'],
        email=data['email'],
        department_id=data['department_id'],
        role=role
    )
    new_user.set_password(data['password'])

    try:
        db.session.add(new_user)
        db.session.commit()
        return jsonify({
            'message': 'User registered successfully',
            'user': new_user.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'Database error: {str(e)}'}), 500


@user_bp.route('/login', methods=['POST'])
def login():
    """用户登录"""
    data = request.get_json()
    if not data or 'email' not in data or 'password' not in data:
        return jsonify({'error': 'Email and password required'}), 400

    user = User.query.filter_by(email=data['email']).first()
    if not user:
        return jsonify({'error': 'Invalid credentials'}), 401

    if not user.check_password(data['password']):
        return jsonify({'error': 'Invalid credentials'}), 401

    # 生成简化token
    token = f'Bearer {user.id}'

    return jsonify({
        'message': 'Login successful',
        'token': token,
        'user': user.to_dict_with_department()
    })


@user_bp.route('/me', methods=['GET'])
def get_current_user():
    """获取当前登录用户信息"""
    user = g.current_user
    return jsonify(user.to_dict_with_department())


@user_bp.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    """获取用户信息"""
    user = User.query.get(user_id)
    if not user:
        return jsonify({'error': 'User not found'}), 404
    return jsonify(user.to_dict_with_department())


@user_bp.route('/users/<int:user_id>', methods=['PUT'])
@require_role('admin')
def update_user(user_id):
    """更新用户信息"""
    user = User.query.get(user_id)
    if not user:
        return jsonify({'error': 'User not found'}), 404

    data = request.get_json()
    if not data:
        return jsonify({'error': 'No data provided'}), 400

    # 更新基本信息
    if 'name' in data:
        user.name = data['name']
    if 'phone' in data:
        user.phone = data['phone']
    if 'email' in data and data['email'] != user.email:
        # 检查邮箱是否已被其他用户使用
        if User.query.filter(User.email == data['email'], User.id != user.id).first():
            return jsonify({'error': 'Email already in use by another user'}), 409
        user.email = data['email']

    # 更新密码
    if 'password' in data:
        user.set_password(data['password'])

    # 更新部门
    if 'department_id' in data:
        department = Department.query.get(data['department_id'])
        if not department:
            return jsonify({'error': 'Department not found'}), 404
        user.department_id = data['department_id']

    # 更新角色
    if 'role' in data:
        if data['role'] not in current_app.config['ROLES']:
            roles = ', '.join(current_app.config['ROLES'])
            return jsonify({'error': f'Invalid role. Valid roles are: {roles}'}), 400
        user.role = data['role']

    try:
        db.session.commit()
        return jsonify({
            'message': 'User updated successfully',
            'user': user.to_dict_with_department()
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'Database error: {str(e)}'}), 500


@user_bp.route('/users/<int:user_id>', methods=['DELETE'])
@require_role('admin')
def delete_user(user_id):
    """删除用户"""
    user = User.query.get(user_id)
    if not user:
        return jsonify({'error': 'User not found'}), 404

    try:
        db.session.delete(user)
        db.session.commit()
        return jsonify({'message': 'User deleted successfully'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'Database error: {str(e)}'}), 500